package com.itqf.filter;

import com.itqf.dao.UserDao;
import com.itqf.dao.impl.UserDaoImpl;
import com.itqf.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * projectName: gpshop
 *
 * @author: 赵伟风
 * time: 2021/7/21 15:04
 * description: 自动登录filter
 */
@WebFilter("/login.jsp")
public class AutoLoginFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        

        HttpServletRequest request = (HttpServletRequest) servletRequest;

        Cookie[] cookies = request.getCookies();

        //存储token的cookie
        Cookie tokenCookie = null;

        if(cookies != null && cookies.length > 0) {

            for (Cookie cookie : cookies) {
                if (cookie.getName().equalsIgnoreCase("token")) {
                    tokenCookie = cookie;
                    break;
                }
            }
        }

        //tokenCookie == null
        if (tokenCookie == null)
        {
            filterChain.doFilter(request,servletResponse);
        }else{

            String token = tokenCookie.getValue();

            UserDao userDao = new UserDaoImpl();
            User user = null;

            try {
                user = userDao.queryUserByToken(token);
            } catch (SQLException e) {
                e.printStackTrace();
            }

            if (user == null){
                filterChain.doFilter(request,servletResponse);
            }else{

                //找到token对应的user
                request.getSession().setAttribute("user", user);
                HttpServletResponse response = (HttpServletResponse) servletResponse;
                response.sendRedirect(request.getContextPath()+"/index.jsp");
            }

        }


    }

    /**
     * Called by the web container to indicate to a filter that it is being
     * taken out of service. This method is only called once all threads within
     * the filter's doFilter method have exited or after a timeout period has
     * passed. After the web container calls this method, it will not call the
     * doFilter method again on this instance of the filter. <br>
     * <br>
     * <p>
     * This method gives the filter an opportunity to clean up any resources
     * that are being held (for example, memory, file handles, threads) and make
     * sure that any persistent state is synchronized with the filter's current
     * state in memory.
     */
    @Override
    public void destroy() {

    }
}
